<?php

class App_Model_DbTable_Domain extends Ext_Db_Table  
{  

    protected $_name = 'domain';
    
    private static $_domain = array();
    
    public function getRowByDomain($domain)
    {    
        if(!$domain)
        {
            return "";
        }
        
        if(isset(self::$_domain['domain'][$domain]))
        {
            return self::$_domain['domain'][$domain];
        }
        
        $db = $this->getAdapter();
        $safe = $db->quoteInto(" domain = ? ", $domain);
        $row = $this->fetchRow($safe);
        
        if (!$row) {
            return "";
        }
        $blogDomain = $row->toArray();
        
        self::$_domain['domain'][$domain] = $blogDomain;
        
        return $blogDomain;
    }
    
    public function addNew($inputArray)
    {
        $row = array();
        if(array_key_exists('domain', $inputArray)) $row['domain'] = $inputArray['domain'];
        if(array_key_exists('userId', $inputArray)) $row['userId'] = $inputArray['userId'];
        if(!$row){
            return "";
        }
        
        try {
            // 插入数据行并返回插入的行数
            $rows_affected = $this->insert($row);
            // 最后插入的数据id   
            $last_insert_id = $this->getAdapter()->lastInsertId();
        }catch (Exception $e){
            trigger_error($e->getMessage(), E_USER_WARNING);
        }
        return $last_insert_id;
    }
    
    public function addOld($inputArray, $domain)
    {
        $row = array();
        if(array_key_exists('userId', $inputArray)) $row['userId'] = $inputArray['userId'];
        if(!$row){
            return "";
        }
        
        try {
            $db = $this->getAdapter();
            $where = $db->quoteInto(" domain = ? ", $domain);
            $rows_affected = $this->update($row, $where);
            if($rows_affected){
                $this->_unsetRow($domain);
            }
        }catch (Exception $e){
            trigger_error($e->getMessage(), E_USER_WARNING);
        }
        
        return "";
    }
    
    private function _unsetRow($domain)
    {
        if(!$domain)
        {
            return "";
        }
        
        $domainOne = $this->getRowByDomain($domain);
        if(!$domainOne)
        {
            return "";
        }
        unset(self::$_domain['domain'][$domain]);
    }
}  

